package com.hangsu.train.hl7;

import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.app.HL7Service;
import ca.uhn.hl7v2.app.ServerConfiguration;
import ca.uhn.hl7v2.llp.MinLowerLayerProtocol;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class HL7Server {

    private static HapiContext context = new DefaultHapiContext();

    @PostConstruct
    public void start() throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                10, 100,
                30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(100));
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        MinLowerLayerProtocol mllp = new MinLowerLayerProtocol();
        mllp.setCharset("UTF-8");
        context.setLowerLayerProtocol(mllp);
        context.setExecutorService(executor);
        ServerConfiguration s = new ServerConfiguration();
        boolean useSecureConnection = false; // are you using TLS/SSL?
        HL7Service ourHl7Server = context.newServer(9999, useSecureConnection);
        ourHl7Server.registerApplication(new MyReceivingApplication());
        ourHl7Server.startAndWait();
    }
}